<template>
  <div class="app-container">
    <div class="container">
      <div class="main page page-list">
        <div class="head-container">
          <el-card shadow="never">
            <div class="search-bar pd">
              <el-form :inline="true" :model="searchModel" size="mini" class="demo-form-inline">
                <el-form-item label="合伙人编号">
                  <el-input v-model="searchModel.id" placeholder="合伙人编号"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input v-model="searchModel.mobile" placeholder="手机号码"></el-input>
                </el-form-item>
                <el-form-item label="提现支付宝账号">
                  <el-input v-model="searchModel.alipayAccount" placeholder="提现支付宝账号"></el-input>
                </el-form-item>
                <el-form-item label="注册时间">
                  <el-date-picker v-model="searchModel.registerTime" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" :default-time="['00:00:00']" value-format='yyyy-MM-dd HH:mm:ss'>
                  </el-date-picker>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="search">查询</el-button>
                  <el-button type="default" @click="reset">重置</el-button>
                  <el-button v-permission="['ADMIN', 'partner::register']" type="default" @click="register">注册</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>

        </div>

        <div class="data-list-wrap">
          <el-card shadow="never">
            <el-table size="mini" v-loading="loading" :data="list" style="width: 100%">
              <el-table-column prop="registerTime" label="注册时间">
              </el-table-column>
              <el-table-column label="基本信息">
                <template slot-scope="scope">
                  <div>姓名：<span class="text-bold-18">{{ scope.row.name ? scope.row.name : "-" }}</span></div>
                  <div>手机号：<span class="text-bold-18">{{ scope.row.mobile }}</span></div>
                  <div>合伙人编号：<span class="text-bold-18">{{ scope.row.id }}</span></div>
                </template>
              </el-table-column>
              <el-table-column label="合伙人级别">
                <template slot-scope="scope">
                  <div><span class="text-bold-18">{{ scope.row.level === 1 ? "一级" : "二级" }}</span></div>

                </template>
              </el-table-column>
              <el-table-column label="提现账号">
                <template slot-scope="scope">
                  <div>支付宝实名：{{ scope.row.alipayName ? scope.row.alipayName : '-' }}</div>
                  <div>
                    支付宝：{{ scope.row.alipayAccount ? scope.row.alipayAccount : "-" }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="分佣模式">
                <template slot-scope="scope">
                  <div v-if="scope.row.partnerCodes[0].commissionMode === 'fixed_mode'">
                    固定百分比模式
                  </div>
                  <div v-if="scope.row.partnerCodes[0].commissionMode === 'cost_mode'">
                    成本模式
                  </div>
                  <div v-if="scope.row.partnerCodes[0].commissionMode === 'stat_mode'">
                    内部结算模式
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="推广分佣信息" width="300px"  v-if="checkPermission(['ADMIN', 'partner::show-benefit-info'])">
                <template slot-scope="scope">
                  <div v-if="scope.row.partnerCodes && scope.row.partnerCodes.length">
                    <div v-for="(item, index) in scope.row.partnerCodes" :key="item.id">
                      <el-divider v-if="index > 0"></el-divider>
                      <div>
                        <span>{{ item.name }}：
                          <span v-if="item.mode === 'fixed_ratio'">
                            <div v-if="item.commissionMode === 'cost_mode'">
                              <div>平台收取合伙人到<span class="text-primary">支付宝</span>成本费率：<span class="text-bold-18">{{
                                (item.costServiceRatio * 100).toFixed(2) }}%</span></div>
                              <div>平台收取合伙人到<span class="text-primary">银行卡</span>成本费率：<span class="text-bold-18">{{
                                (item.safePayBankCostServiceRatio * 100).toFixed(2) }}%</span></div>
                              <div>合伙人到客户默认费率：<span class="text-bold-18">{{ (item.serviceRatio * 100).toFixed(2)
                              }}%</span></div>
                            </div>
                            <div v-else>
                              <div class="text-bold-18">{{ item.benefitRatio * 100 }}%毛利</div>
                              <div>父级分佣：{{ item.fatherBenefitRatio * 100 }}%毛利</div>
                              <div>收费：<span class="text-bold-18">{{ item.serviceRatio * 100 }}%</span></div>
                            </div>

                          </span>

                          <span v-if="item.mode === 'fixed_amount'">
                            <span class="text-bold-18">{{ item.benefit / 100 }}</span>
                            <span v-if="item.fatherPartnerId" class="text-danger"> (父级分佣： {{ item.fatherBenefit / 100 }})
                            </span>
                            <span>(收费：<span class="text-bold-18">{{ item.serviceUnitPrice / 100 }}</span>)</span>
                          </span>
                        </span>
                      </div>

                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="业务备注">
                <template slot-scope="scope">
                  {{ scope.row.remark ? scope.row.remark : "-" }}
                </template>
              </el-table-column>
              <el-table-column label="账户余额" width="100" v-if="checkPermission(['ADMIN', 'partner::show-account-info'])">
                <template slot-scope="scope">
                  ¥ <span class="text-bold-18">{{ scope.row.moneyLeft / 100 }}</span>
                  <div v-if="scope.row.moneyLeft > 0">
                    <el-button v-permission="['ADMIN', 'partner-withdraw-record-batch::create']" type="text"
                      @click="withdraw(scope.row)">提现</el-button>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="状态">
                <template slot-scope="scope">
                  <span class="text-success" v-if="scope.row.securityStatus === 0">正常</span>
                  <span class="text-danger" v-if="scope.row.securityStatus === -1">已冻结</span>
                  <div class="text-danger" v-if="scope.row.securityRemark">({{ scope.row.securityRemark }})</div>
                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" width="180">

                <template slot-scope="scope">
                  <div class="operations">
                    <el-button style="margin-left:10px;" v-permission="['ADMIN']" size="mini" type="text" plain
                      @click="doLogin(scope.row)">
                      登录
                    </el-button>
                    <el-button style="margin-left:10px;" v-permission="['ADMIN', 'partner::update-benefit']" size="mini"
                      type="text" plain @click="openUpdateBenefitDialog(scope.row)">
                      设置分佣
                    </el-button>
                    <el-button v-permission="['ADMIN', 'partner::update-partner-info']" size="mini" type="text" plain
                      @click="openUpdatePartnerInfoDialog(scope.row)">
                      修改信息
                    </el-button>
                    <el-button v-permission="['ADMIN', 'partner::update-partner-security-status']" size="mini" type="text" plain
                      @click="openUpdatePartnerSecurityStatusDialog(scope.row)">
                      修改用户状态
                    </el-button>

                    <el-popover placement="top" width="200" :ref="'resetPasswrod' + scope.row.id" trigger="click">
                      <p>确定重置该用户密码吗？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="
                          $refs['resetPasswrod' + scope.row.id].doClose()
                          ">取消</el-button>
                        <el-button :loading="opLoading" type="primary" size="mini"
                          @click="doResettingPassword(scope.row.id)">确定</el-button>
                      </div>
                      <el-button v-permission="['ADMIN', 'partner::reset-partner-password']" size="mini" type="text"
                        style="margin-left:10px;" slot="reference" :value="scope.row.id">
                        重置密码
                      </el-button>
                    </el-popover>

                  </div>

                </template>
              </el-table-column>
            </el-table>
            <div class="paging-wrap">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="searchModel.pageNo" :page-sizes="[10, 20, 50, 100]" :page-size="searchModel.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="searchModel.count">
              </el-pagination>
            </div>
          </el-card>
        </div>

        <!-- 注册合伙人 -->
        <el-dialog title="注册合伙人" :close-on-click-modal="false" :modal-append-to-body="false" class="dialog-action"
          width="50%" :visible.sync="dialogRegister">
          <el-form :model="registerForm" label-width="150px" :rules="rules" ref="registerForm">
            <el-alert style="margin-bottom: 10px" title="密码注册后随机生成，请告知合伙人并及时修改" type="warning">
            </el-alert>
            <el-form-item label="手机号" prop="mobile" required>
              <el-input type="number" v-model="registerForm.mobile" placeholder="手机号"></el-input>
            </el-form-item>

            <el-form-item label="姓名" prop="name">
              <el-input v-model="registerForm.name" placeholder="姓名"></el-input>
            </el-form-item>

            <el-form-item label="分佣方式" prop="commissionMode">
              <el-radio-group v-model="registerForm.commissionMode">
                <el-radio-button label="fixed_mode">固定百分比模式</el-radio-button>
                <el-radio-button label="cost_mode">成本模式</el-radio-button>
                <el-radio-button label="stat_mode">内部结算模式</el-radio-button>
              </el-radio-group>

            </el-form-item>

            <el-form-item label="业务备注" prop="remark">
              <el-input type="textarea" v-model="registerForm.remark" placeholder="业务备注"></el-input>
            </el-form-item>

            <el-form-item label="密码">
              <span class="text-danger">{{ registerForm.password }}</span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogRegister = false">取 消</el-button>
            <el-button :loading="opLoading" type="primary" @click="doRegister">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 合伙人提现 -->
        <el-dialog title="合伙人提现" :close-on-click-modal="false" :modal-append-to-body="false" class="dialog-action"
          width="50%" :visible.sync="dialogWithdraw">
   
          <el-form :model="withdrawForm" label-width="150px" :rules="withdrawRules" ref="withdrawForm">
            <el-form-item label="打款方式">
              <el-radio-group v-model="isOffline" >
                <el-radio-button  :label="0">线上打款</el-radio-button>
                <el-radio-button :label="1">线下打款</el-radio-button>
              </el-radio-group>

            </el-form-item>
            <el-form-item label="打款方支付宝" v-if="!isOffline">
              <span>{{ sysTransAccount.alipayNickName }}(余额：{{ sysTransAccount.bookBalance }} 元)</span>
            </el-form-item>

            <el-form-item label="合伙人账户余额" prop="moneyLeft">
              <span>{{ withdrawForm.moneyLeft / 100 }} 元</span>
            </el-form-item>
            <el-form-item label="提现金额" prop="transferMoney">
              <el-input v-model="withdrawForm.transferMoney" placeholder="金额" type="number"
                style="width: 200px;margin-right:8px;"></el-input>元
                <div class="text-info">上月分佣总金额：{{ lastSettleMoney }}元</div>
            </el-form-item>

            <el-form-item label="收款支付宝姓名" prop="alipayName" v-if="!isOffline">
              <el-input v-model="withdrawForm.alipayName" placeholder="收款支付宝姓名"></el-input>
            </el-form-item>

            <el-form-item label="收款支付宝账号" prop="alipayAccount" v-if="!isOffline">
              <el-input v-model="withdrawForm.alipayAccount" placeholder="收款支付宝账号"></el-input>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogWithdraw = false">取 消</el-button>
            <el-button :loading="opLoading" type="primary" @click="doWithdraw">确 定</el-button>
          </div>

        </el-dialog>


        <!-- 合伙人提现 -->
        <el-dialog :close-on-click-modal="false" :modal-append-to-body="false" class="dialog-action" width="30%"
          :visible.sync="dialogWithdrawDealing">
          <div v-loading="queryWithdrawLoading" :element-loading-text="'提现处理中: ' + timerCount" class="withdrawTipBox">
            <div v-if="withdrawResult.status === 'failed'">
              提现失败：{{ withdrawResult.errorMsg }}
            </div>
            <div v-if="withdrawResult.status === 'payed'">
              提现成功！
            </div>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button :loading="opLoading" type="primary" @click="dialogWithdrawDealing = false">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog :title="'设置分佣 ' + benefitForm.id" :close-on-click-modal="false" :modal-append-to-body="false"
          class="dialog-action" width="60%" :visible.sync="updateBenefitDialog">
          <el-form :model="benefitForm" label-width="227px" ref="benefitForm">

            <!-- <div v-if="item.mode === 'fixed_amount'">
                  <span>合伙人分佣：</span>
                  <el-input type="number" v-model="item.benefit"></el-input>
                  <div v-if="item.fatherPartnerId">
                    <span>父级合伙人分佣：</span>
                    <el-input type="number" v-model="item.fatherBenefit"></el-input>
                  </div>

                  <span>收费：</span>
                  <el-input type="number" v-model="item.serviceUnitPrice"></el-input>
             </div> -->
            <div  v-for="item in benefitForm.partnerCodes" :key="item.id">
               <el-form-item label="分佣方式" prop="commissionMode">
                            <el-radio-group v-model="item.commissionMode">
                                <el-radio-button label="fixed_mode">固定比例</el-radio-button>
                                <el-radio-button label="cost_mode">成本模式</el-radio-button>
                                <el-radio-button label="stat_mode">内部结算模式</el-radio-button>
                            </el-radio-group>
               </el-form-item>

                        <el-form-item label="合伙人旗下商户到户默认费率" prop="serviceRatio">
                            <el-input type="number" v-model="item.serviceRatio"
                  placeholder="请输入合伙人旗下商户到户默认费率 0.001表示0.1%即千1"></el-input>
                        </el-form-item>

                        <el-form-item label="合伙人旗下商户到卡默认费率" prop="bankServiceRatio">
                            <el-input type="number" v-model="item.bankServiceRatio"
                  placeholder="请输入合伙人旗下商户到户默认费率 0.001表示0.1%即千1"></el-input>
                        </el-form-item>

                        <el-form-item  label="分佣比例" v-if="item.commissionMode === 'fixed_mode' || item.commissionMode === 'stat_mode'"  prop="benefitRatio">
                            <el-input v-model="item.benefitRatio" placeholder="请输入分佣比例 0.1表示10%"></el-input>
                        </el-form-item>

                        <el-form-item label="到户成本" v-if="item.commissionMode === 'cost_mode'" prop="costServiceRatio">
                                <el-input v-model="item.costServiceRatio"  placeholder="到户成本"> </el-input>
                        </el-form-item>

                        <el-form-item label="到卡成本" v-if="item.commissionMode === 'cost_mode'" prop="safePayBankCostServiceRatio">
                                <el-input v-model="item.safePayBankCostServiceRatio"  placeholder="到卡成本"> </el-input>
                        </el-form-item>
              </div>
  
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="updateBenefitDialog = false">取 消</el-button>
            <el-button :loading="opLoading" type="primary" @click="doUpdateBenefit">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog :title="'修改信息 ' + updatePartnerInfoForm.id" :close-on-click-modal="false" :modal-append-to-body="false"
          class="dialog-action" width="50%" :visible.sync="updatePartnerInfoDialog">
          <el-form :model="updatePartnerInfoForm" label-width="140px" ref="updatePartnerInfoForm">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="updatePartnerInfoForm.name" placeholder="姓名"></el-input>
            </el-form-item>
            <el-form-item label="提现支付宝姓名" prop="alipayName">
              <el-input v-model="updatePartnerInfoForm.alipayName" placeholder="提现支付宝姓名"></el-input>
            </el-form-item>

            <el-form-item label="提现支付宝账号" prop="alipayAccount">
              <el-input v-model="updatePartnerInfoForm.alipayAccount" placeholder="提现支付宝账号"></el-input>
            </el-form-item>

            <el-form-item prop="wechatQrCode" label="网站微信二维码">
              <div class="businessLicense-content">
                <el-upload action="/api/admin/image" list-type="picture-card" :class="{ disabled: uploadDisabled }"
                  :limit="1" ref="upload" :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload"
                  :on-remove="handleRemove1" :on-preview="handlePictureCardPreview1" :file-list="wechatQrCode">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" :modal-append-to-body="false"
                  append-to-body>
                  <img width="100%" :src="wechatQrCodeUrl" alt="" />
                </el-dialog>
              </div>
            </el-form-item>

            <el-form-item label="结算周期" prop="settlePeriod">
              <el-radio-group v-model="updatePartnerInfoForm.settlePeriod">
                <el-radio-button label="day">按日结算</el-radio-button>
                <el-radio-button label="month">按月结算</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="余额每日自动提现" prop="autoWithdraw">
              <el-switch v-model="updatePartnerInfoForm.autoWithdraw" active-color="#13ce66">
              </el-switch>
            </el-form-item>

            <el-form-item label="业务备注" prop="remark">
              <el-input type="textarea" v-model="updatePartnerInfoForm.remark" placeholder="业务备注"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="updatePartnerInfoDialog = false">取 消</el-button>
            <el-button :loading="opLoading" type="primary" @click="doUpdatePartnerInfo">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog :title="'修改用户状态 ' + updatePartnerSecurityStatusForm.id" :close-on-click-modal="false"
          :modal-append-to-body="false" class="dialog-action" width="50%"
          :visible.sync="updatePartnerSecurityStatusDialog">
          <el-form :model="updatePartnerSecurityStatusForm" label-width="100px" ref="updatePartnerSecurityStatusForm">
            <el-form-item label="用户状态" prop="name">
              <el-radio-group v-model="updatePartnerSecurityStatusForm.securityStatus">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="-1">冻结</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="updatePartnerSecurityStatusForm.securityRemark"
                placeholder="备注"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="updatePartnerSecurityStatusDialog = false">取 消</el-button>
            <el-button :loading="opLoading" type="primary" @click="doUpdatePartnerSecurityStatus">确 定</el-button>
          </div>
        </el-dialog>


        <!-- 重置密码 -->
        <el-dialog title="新密码" :close-on-click-modal="false" :modal-append-to-body="false" class="dialog-action"
          width="50%" :visible.sync="resettingPasswordDialog">
          <el-form :model="resettingForm" label-width="100px">
            <el-form-item label="新密码:">
              <span class="text-danger">{{ resettingForm.password }}</span>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button :loading="opLoading" type="primary" @click="doCopy($event)">复制</el-button>
          </div>
        </el-dialog>

      </div>
    </div>
  </div>
</template>


<script>
import Cookies from 'js-cookie'
import {
  searchPartner,
  registerPartner,
  updatePartnerSecurityStatus,
  updatePartnerInfo,
  updatePartnerBenefit,
  loginPartner,
  createPartnerWithdrawRecordBatch,
  getPartnerLastMonthSettleBenefit,
  resetPartnerPassword
} from "@/api/business";
import clipboard from "../../utils/clipboard";
import checkPermission from "@/utils/permission";
import {
  queryPartnerWithdrawTransStatus,
  querySystemPartnerWithdrawTransAccount
} from "@/api/partnerWithdraw"
const defaultModel = {
  registerTime: null,
  level: 1,
  mobile: null,
  pageNo: 1,
  pageSize: 10,
  count: 0,
};
export default {
  data() {
    return {
      searchModel: _.cloneDeep(defaultModel),
      list: [],
      loading: false,
      curData: {},
      opLoading: false,
      wechatQrCode: [
        {
          uid: "",
          url: ""
        }
      ],
      wechatQrCodeUrl: "",
      dialogVisible: false,
      uploadDisabled: false,
      form: { amount: 0 },
      dialogRegister: false,
      registerForm: {
        level: 1
      },
      rules: {
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        commissionMode: [{ required: true, message: "请选择分佣模式", trigger: "blur" }],
      },

      benefitForm: {
        id: "",
      },
      updateBenefitDialog: false,

      updatePartnerInfoDialog: false,
      updatePartnerInfoForm: {},

      updatePartnerSecurityStatusDialog: false,
      updatePartnerSecurityStatusForm: {},

      dialogWithdraw: false,

      withdrawForm: {
      },
      isOffline: null,
      withdrawRules: {
        transferMoney: [
          { required: true, message: "请输入金额", trigger: "blur" },
        ],
      },


      dialogWithdrawDealing: false,
      withdrawResult: {
        dealing: true,
        status: "wait_pay"
      },
      queryWithdrawLoading: false,

      timer: null,
      timerCount: 10,

      sysTransAccount: {
        alipayNickName: "",
        userId: "",
        bookBalance: "",
        safePayBookAccountId: "",
      },
      resettingPasswordDialog: false,
      resettingForm: {
        password: "",
      },

      lastSettleMoney: 0, //上月分佣总金额
    };
  },

  components: {},
  methods: {
    checkPermission,
    
    withdraw(row) {
      this.querySysAccount()
      this.dialogWithdraw = true;
      this.withdrawForm = _.cloneDeep(row);
      this.isOffline = null;
      this.queryPartnerLastSettleMoney(row.id);
    },

    queryPartnerLastSettleMoney(id) {
      getPartnerLastMonthSettleBenefit({id}).then(resp=>{
        if (resp.success) {
          this.lastSettleMoney = resp.data;
        }
      })
    },

    querySysAccount() {
      querySystemPartnerWithdrawTransAccount().then(resp => {
        if (resp.success) {
          this.sysTransAccount = resp.data;
        }
      })
    },

    stopTimer() {
      if (this.timer !== null) {
        clearInterval(this.timer);
        this.timer = null;
      }
      this.timerCount = 10;
    },

    doWithdraw() {
      let form = {
        partnerId: this.withdrawForm.id,
        transferMoney: (this.withdrawForm.transferMoney * 100).toFixed(),
        alipayName: this.withdrawForm.alipayName,
        alipayAccount: this.withdrawForm.alipayAccount,
        isOffline: this.isOffline
      };
      this.$refs["withdrawForm"].validate((valid) => {
        if (valid) {
          this.opLoading = true;
          createPartnerWithdrawRecordBatch(form).then((resp) => {
            if (resp.success) {
              if (!this.isOffline) {
                //轮询转账结果
              this.withdrawResult = {};
              //开始查询结果
              this.dialogWithdrawDealing = true;
              this.queryWithdrawLoading = true;
              let form = { partnerWithdrawRecordBatchId: resp.data.id }
              this.timer = setInterval(() => {
                if (this.timerCount >= 0) {
                  this.timerCount--
                }
                queryPartnerWithdrawTransStatus(form).then((resp) => {
                  if (resp.success) {
                    let data = resp.data;
                    this.withdrawResult = data;
                    if (!data.dealing) {
                      //停止转圈
                      this.queryWithdrawLoading = false;
                      //停止轮询
                      this.stopTimer()
                    }
                    if (data.status === 'payed') {
                      //提现成功了提现操作框关闭掉
                      this.dialogWithdraw = false;
                      this.getList();
                    }
                  } else {
                    //停止轮询
                    this.stopTimer()
                  }
                })
              }, 1000);
              } else {
                 //提现成功了提现操作框关闭掉
                 this.dialogWithdraw = false;
                 this.$notify({
                  title: "操作成功",
                  type: "success",
                  duration: 2500,
                });
                 this.getList();
              }
            }
            this.opLoading = false;

          });
        } else {
          return false;
        }
      });
    },
    openUpdatePartnerInfoDialog(row) {
      this.updatePartnerInfoDialog = true;
      this.updatePartnerInfoForm = _.cloneDeep(row);
      this.wechatQrCode[0] = {
        uid: this.updatePartnerInfoForm.uid,
        url: this.updatePartnerInfoForm.wechatQrCode
      };
    },

    doLogin(row) {
      let form = {
        userId: row.id,
      };
      loginPartner(form).then((data) => {
        if (data.success) {
          let resp = data.data;
          if (resp) {
            window.open("http://" + resp);
          }
        }
      });
    },

    openUpdatePartnerSecurityStatusDialog(row) {
      this.updatePartnerSecurityStatusDialog = true;
      this.updatePartnerSecurityStatusForm = _.cloneDeep(row);
    },

    doUpdatePartnerSecurityStatus() {
      this.opLoading = true;
      let form = {
        id: this.updatePartnerSecurityStatusForm.id,
        securityStatus: this.updatePartnerSecurityStatusForm.securityStatus,
        securityRemark: this.updatePartnerSecurityStatusForm.securityRemark,
      };
      updatePartnerSecurityStatus(form).then((resp) => {
        if (resp.success) {
          this.$notify({
            title: "修改成功",
            type: "success",
            duration: 2500,
          });
          this.updatePartnerSecurityStatusDialog = false;
          this.search();
        }
        this.opLoading = false;
      });
    },

    doUpdatePartnerInfo() {
      this.opLoading = true;
      let form = {
        id: this.updatePartnerInfoForm.id,
        name: this.updatePartnerInfoForm.name,
        remark: this.updatePartnerInfoForm.remark,
        settlePeriod: this.updatePartnerInfoForm.settlePeriod,
        alipayName: this.updatePartnerInfoForm.alipayName,
        alipayAccount: this.updatePartnerInfoForm.alipayAccount,
        autoWithdraw: this.updatePartnerInfoForm.autoWithdraw,
        wechatQrCode: this.updatePartnerInfoForm.wechatQrCode
      };
      updatePartnerInfo(form).then((resp) => {
        if (resp.success) {
          this.$notify({
            title: "修改成功",
            type: "success",
            duration: 2500,
          });
          this.updatePartnerInfoDialog = false;
          this.search();
        }
        this.opLoading = false;
      });
    },

    openUpdateBenefitDialog(row) {
      this.updateBenefitDialog = true;
      this.benefitForm = _.cloneDeep(row);
      this.benefitForm.partnerCodes.forEach((element) => {
        element.benefit = element.benefit / 100;
        element.serviceUnitPrice = element.serviceUnitPrice / 100;
        element.fatherBenefit = element.fatherBenefit / 100;
      });
    },
    doUpdateBenefit() {
      let partnerCodes = _.cloneDeep(this.benefitForm.partnerCodes);

      for (let i = 0; i < partnerCodes.length; i++) {
        let code = partnerCodes[i];
        if (code.benefit === "") {
          this.$notify({
            title: code.name + "设置不能为空",
            type: "error",
            duration: 2500,
          });
          return;
        }
        code.benefit = (code.benefit * 100).toFixed();
        code.serviceUnitPrice = (code.serviceUnitPrice * 100).toFixed();
        code.fatherBenefit = (code.fatherBenefit * 100).toFixed();

        delete code.name;
      }
      this.$refs["benefitForm"].validate((valid) => {
        if (valid) {
          this.opLoading = true;
          updatePartnerBenefit({
            id: this.benefitForm.id,
            partnerCodes,
          }).then((resp) => {
            if (resp.success) {
              this.$notify({
                title: "修改成功",
                type: "success",
                duration: 2500,
              });
              this.updateBenefitDialog = false;
              this.search();
            }
            this.opLoading = false;
          });
        } else {
          return false;
        }
      });
    },

    doRegister() {
      let partner = _.cloneDeep(this.registerForm);
      this.$refs["registerForm"].validate((valid) => {
        if (valid) {
          this.opLoading = true;
          registerPartner(partner).then((resp) => {
            if (resp.success) {
              this.$notify({
                title: "注册成功",
                type: "success",
                duration: 2500,
              });
              this.registerForm.password = resp.data.password;
              this.search();
            }
            this.opLoading = false;
          });
        } else {
          return false;
        }
      });
    },
    //注册
    register() {
      this.dialogRegister = true;
      this.registerForm = {
        level: 1
      };
    },

    //复制链接
    doCopy(e) {
      let password = this.resettingForm.password
      let info = password
      clipboard(info, e);
    },


    // 确认重置密码
    doResettingPassword(id) {
      this.opLoading = true;
      let form = {
        id: id
      }
      resetPartnerPassword(form).then((resp => {
        if (resp.success) {
          this.$notify({
            title: "重置成功",
            type: "success",
            duration: 2500,
          });
          this.resettingForm.password = resp.data
          this.resettingPasswordDialog = true;
          this.$refs["resetPasswrod" + id].doClose();
          this.search();
        } else {
          this.$message.error(resp.resultMessage);
        }
        this.opLoading = false;
      })).catch(err => {

      })
    },

    search() {
      this.getList(1);
    },

    getList(pageNo) {
      var self = this;
      this.loading = true;
      if (pageNo != undefined) {
        this.searchModel.pageNo = pageNo;
      }

      let searchModel = _.cloneDeep(this.searchModel);
      searchPartner(this.compileSearchModel(searchModel))
        .then((data) => {
          self.searchModel.pageNo = ++data.pageNo;
          self.searchModel.count = data.count;
          self.searchModel.pageSize = data.pageSize;
          self.list = data.data;
          self.loading = false;
        })
        .catch((err) => { });
    },
    reset() {
      this.searchModel = _.cloneDeep(defaultModel);
      this.getList();
    },
    compileSearchModel(searchModel) {
      searchModel.pageNo = searchModel.pageNo - 1;

      if (searchModel.registerTime && searchModel.registerTime.length) {
        searchModel["minRegisterTime"] = searchModel.registerTime[0];
        searchModel["maxRegisterTime"] = searchModel.registerTime[1];
      }
      delete searchModel.registerTime;

      return searchModel;
    },

    handleAvatarSuccess1(res, file) {
      this.updatePartnerInfoForm.wechatQrCode = res.data;
      this.wechatQrCode[0] = this.updatePartnerInfoForm.wechatQrCode;

    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("上传大小不能超过 5MB!");
      }
      return isLt5M;
    },
    handleRemove1(file, fileList) {
      this.updatePartnerInfoForm.wechatQrCode = "";
    },
    handlePictureCardPreview1(file) {
      this.wechatQrCodeUrl = file.url;
      this.dialogVisible = true;
    },
    //修改分页
    handleSizeChange(val) {
      this.searchModel.pageSize = val;
      this.getList(1);
    },
    //修改页面
    handleCurrentChange(val) {
      this.getList(val);
    },
    init() {
      this.getList(1);
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style lang="scss" scoped>
.operations {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.images-body {
  width: 56px;
  height: 56px;
  border-radius: 8px;
}

.withdrawTipBox {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
